package com.zj.thread.callable;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicBoolean;

public class CompletionServiceTest {
    static AtomicBoolean taskflag=new AtomicBoolean(false);

    public static void main(String[] args) {
        ExecutorService executor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
        CompletionService cs = new ExecutorCompletionService<Integer>(executor);

        //创建一个Callable，3秒后返回String类型
        System.out.println("提交任务之前 "+getStringDate());
        int taskNums=9;
        for(int i=0;i<taskNums;i++){
            taskflag.set(true);
            cs.submit(new MyTask(i));
        }
        cs.submit(new CountTask(cs,taskflag,taskNums));

        System.out.println("提交任务之后，获取结果之前 "+getStringDate());
        executor.shutdown();
    }
    public static String getStringDate() {
        Date currentTime = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss");
        String dateString = formatter.format(currentTime);
        return dateString;
    }

    static class CountTask implements Callable<Integer> {
        CompletionService cs;
        AtomicBoolean taskflag;
        int taskCount;

        CountTask(CompletionService cs, AtomicBoolean taskflag, int num) {
            this.cs = cs;
            this.taskflag = taskflag;
            this.taskCount = num;
        }

        @Override
        public Integer call() throws Exception {
            System.out.println("任务结束:" + CallableTest.getStringDate());
            int count = 0;
            for (int i = 0; i < taskCount; i++) {
                try {

                    int res = (int) cs.take().get();
                    System.out.println("futures[" + i + "],res:" + res);
                    count++;
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            System.out.println(taskflag.get());
            taskflag.set(false);
            System.out.println("count:" + count);
            System.out.println("最后时间:" + CallableTest.getStringDate());
            System.out.println(taskflag.get());
            return 1;
        }
    }

}
